<template>
  <div>
    <Header></Header>

    <div class="m-blog">
      <h3>{{ blog.title }}</h3>
      <router-link :to="{name: 'BlogEdit', params: {blogId: blog.id}}">
        <el-button type="primary" size="small" icon="el-icon-edit" circle v-if="isAuthor"></el-button>
      </router-link>
      <el-button id="deleteBtn" type="danger" size="small" icon="el-icon-delete" circle @click="deleteBlog"
                 v-if="isAuthor"></el-button>
      <el-divider></el-divider>
      <div class="markdown-body" v-html="blog.content"></div>
    </div>

  </div>
</template>

<script>
import Header from "@/components/Header"
import 'github-markdown-css'

export default {
  name: "BlogDetail",
  components: {Header},
  data() {
    return {
      blog: {
        title: "",
        content: "",
        id: ""
      },
      isAuthor: false
    }
  },
  methods: {
    deleteBlog() {
      const _this = this;
      if (_this.blog.id) {
        _this.$confirm('此操作将删除该博客, 确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.$axios.delete('/blog/' + _this.blog.id, {
            headers: {
              "Authorization": localStorage.getItem("token")
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });

              _this.$router.push('/');
            } else {
              this.$message({
                type: 'warning',
                message: '删除失败!' + res.data.msg
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      } else {
        _this.$message.error('删除失败，文章不存在');
        _this.$router.push('/');
      }
    }
  },
  created() {
    const _this = this;
    const blogId = this.$route.params.blogId;

    _this.$axios.get('/blog/' + blogId)
        .then(res => {
          const blog = res.data.data;
          _this.blog.id = blog.id;
          _this.blog.title = blog.title;

          const MarkdownIt = require("markdown-it");
          const md = new MarkdownIt();

          _this.ownBlog = (blog.userId === _this.$store.getters.getUser.id)

          _this.blog.content = md.render(blog.content);
        })

  }
}
</script>

<style scoped>
.m-blog {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  min-height: 700px;
  padding: 20px 15px;
}

#deleteBtn {
  margin-left: 20px;
}
</style>